<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="images/chang.ico">
  <title>相册</title>
  <!-- 动画库 -->
  <link rel="stylesheet" href="./css/animate.min.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link rel="stylesheet" href="./css/normalize.css">
  <link href="css/common.css" rel="stylesheet">
  <link rel="stylesheet" href="./css/photos.css">
  <!-- Bootstrap -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
    integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
  <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
    integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous">
    </script>
  <!-- 字体图标 -->
  <link rel="stylesheet" href="./css/font-awesome.min.css">
  <!-- 点击爱心 -->
  <script src="./js/love.js"></script>
  <!-- 瀑布流 -->
  <script src="./js/waterFall.js"></script>
  <!-- 大图查看 -->
  <script src="./js/viewer.js"></script>
  <!-- L2Dwidget.js L2D网页动画人物 -->
  <script src="https://eqcn.ajz.miesnfu.com/wp-content/plugins/wp-3d-pony/live2dw/lib/L2Dwidget.min.js"></script>
  <script>
    L2Dwidget.init({
      "model": {
        "jsonPath": "https://unpkg.com/live2d-widget-model-tororo@1.0.5/assets/tororo.model.json",
        "scale": 1,
        "hHeadPos": 0.5,
        "vHeadPos": 0.618
      },
      "display": {
        "position": "right",
        "width": 100,
        "height": 150,
        "hOffset": -58,
        "vOffset": -53
      },
      "mobile": {
        "show": true,
        "scale": 0.5
      },
      "react": {
        "opacityDefault": 1.5,
        "opacityOnHover": 0.2
      }
    });
  </script>
</head>

<body>
  <header>
    <!-- 头部 -->
    <header>
      <nav class="navbar navbar-inverse">
        <div class="container-fluid">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
              data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="./index.html">首页</a>
          </div>

          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
              <li><a href="./photos.html?id=1">相册</a></li>
              <li><a href="./video.html">视频</a></li>
              <li><a href="./game.html">游戏</a></li>
            </ul>
            <form class="navbar-form navbar-left">
              <div class="form-group">
                <input type="text" class="form-control searchInput" placeholder="Search">
              </div>
              <button type="submit" class="btn btn-default" onclick="search()">搜索</button>
            </form>
            <!-- 文件上传表单 -->
            <form class="navbar-form navbar-left" id="uploadForm">
              <input type="file" name="fileUpload" id="fileUpload" style="opacity: 0;">
            </form>
            <!-- 音乐控件 -->
            <div class="music navbar-header">
              <img src="" alt="">
              <div class="banner">
                <span></span>
              </div>
              <div class="musicControls">
                <span>
                  <i class="fa fa-backward"></i>
                </span>
                <span>
                  <i class="fa fa-pause"></i>
                  <!-- <i class="fa fa-pause"></i> -->
                  <!-- <i class="fa fa-stop"></i> -->
                </span>
                <span>
                  <i class="fa fa-forward"></i>
                </span>
              </div>
              <audio id="audio" src=""></audio>
            </div>
            <ul class="nav navbar-nav navbar-right">
              <li>
                <a href="#" onclick="deletePic()">删除图片</a>
              </li>
              <!-- 文件上传点击按钮 -->
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                  aria-expanded="false">上传图片 <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#" onclick="upload()">本地文件上传</a></li>
                  <li role="separator" class="divider"></li>
                  <li><a href="#" onclick="addUrl()">添加图片地址</a></li>
                </ul>
              </li>
            </ul>
          </div>

        </div>
      </nav>
    </header>
  </header>
  <main>
    <!-- 相册列表 -->
    <div class="row" id="photoList"></div>
    <div class="toTop">
      <i class="fa fa-chevron-up"></i>
    </div>
  </main>
  <!-- 封装请求 -->
  <script>
    const BASE_URL = 'http://121.37.209.61:3000'
    const getAction = (url, params) => {
      return new Promise((resolve, reject) => {
        $.ajax({
          url: BASE_URL + url,
          params,
          type: 'get',
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    }
    const postAction = (url, data) => {
      return new Promise((resolve, reject) => {
        $.ajax({
          url: BASE_URL + url,
          data,
          type: 'post',
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    }

    //请求图片
    const getPhotos = async () => {
      try {
        const res = await getAction('/photos')
        if (res) {
          let photoList = res.map(item => {
            return item.url
          })
  
          // 瀑布流
          let dom = document.querySelector('#photoList');
          waterFallFlow(dom, photoList, 220);
          // 大图查看
          viewer(document.querySelector('#photoList'))
        }
      } catch (e) {
        console.log(e);
      }
    }

    //上传本地图片
    $('#fileUpload').on('change', function () {
      let file = this.files[0]
      let formData = new FormData()
      formData.append('img', file)
      console.log(formData.get('img'));
      $.ajax({
        url: 'http://121.37.209.61:3000/photos/upload',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: (res) => {
          console.log(res);
          getPhotos()
        },
        fail: (err) => {
          console.log(err);
        }
      })
    })

    //添加图片地址
    function addUrl() {
      // 记录当前滚动位置
      let imgUrl = window.prompt('图片url地址')
      if (imgUrl != null && imgUrl != "") {
        $.ajax({
          url: 'http://121.37.209.61:3000/photos/add',
          type: 'post',
          data: {
            img: imgUrl
          },
          success: (res) => {
            console.log(res);
            getPhotos()
          },
          fail: (err) => {
            console.log(err);
          },
          complete: () => {
          }
        })
      } else {
        console.log('空');
      }
    }

    //删除图片
    const deletePhotos = async (idList) => {
      try {
        const res = await postAction('/photos/delete', { idList })
        if (res.status == 1) {
          getPhotos()
          localStorage.removeItem('idList')
        }
      } catch (e) {
        console.log(e);
      }
    }
  </script>
  <!-- 封装事件方法 -->
  <script>
    //阻止默认事件
    $('.navbar-form').on('submit', function (e) {
      e.preventDefault()
    })
    $('.thumbnail').on('click', function (e) {
      e.preventDefault()
    })
    getPhotos()
    //返回顶部
    $('.toTop').on('click', function (e) {
      let timeObj = setInterval(() => {
        window.scrollBy(0, -30);
        if (document.documentElement.scrollTop <= 0) {
          document.documentElement.scrollTop = 0
          clearTimeout(timeObj)
        }
      }, 10)

    })
    //搜索按钮
    function search(e) {
      let inputContent = $('.searchInput').val()
    }
    //代理点击上传表单
    function upload() {
      $('#fileUpload').click()
    }
    //事件锁关闭
    let lock = false
    //点击删除图片
    function deletePic() {
      let idList = JSON.parse(localStorage.getItem('idList')) || [] //初始化id列表
      lock = true //事件锁开启
      if (lock) { //事件锁开启状态下，再次点击删除图片 == 提交到后端
        console.log(idList);
        if (idList.length) {
          deletePhotos(idList)
        }
      }
      $('.check').css({
        'display': 'block'
      })
      $('.item').on('click', function (e) {
        //阻止事件冒泡
        e.stopPropagation()
        let id = e.currentTarget.getAttribute('data-id')
        if (idList.includes(id)) {
          let index = idList.indexOf(id)
          idList.splice(index, 1)
          localStorage.setItem('idList', JSON.stringify(idList))
          e.currentTarget.childNodes[1].checked = false
        } else {
          idList.push(id)
          localStorage.setItem('idList', JSON.stringify(idList))
          e.currentTarget.childNodes[1].checked = true
        }
      })
      //监听鼠标点击空白
      $('.row').on('click', function () {
        localStorage.removeItem('idList')
        //清除所有选中的样式
        for (let i = 0; i < $('.check').length; i++) {
          $('.check')[i].checked = false
        }
        lock = false //事件锁关闭
        //清除事件监听
        $('.item').unbind('click')
        //复选框不可见
        $('.check').css({
          'display': 'none'
        })
      })
    }
  </script>
  <!-- 音乐控件 -->
  <script>
    let musicList = [] //初始化一个音乐列表
    let musicIndex = 0 //初始化当前播放序号
    let audio = document.querySelector('#audio') //初始化播放器
    //监听播放结束
    audio.addEventListener('ended', function () {
      getMusic(++musicIndex)
    })
    $('.musicControls .fa').on('mousedown', function (e) {
      //播放暂停
      if ($(this)[0].classList[1] == 'fa-play') {
        console.log('切换到暂停');
        $(this)[0].classList.replace('fa-play', 'fa-pause')
        document.querySelector('.music img').style.animationPlayState = 'running' //开始旋转
        audio.play()
      } else if ($(this)[0].classList[1] == 'fa-pause') {
        console.log('切换到播放');
        $(this)[0].classList.replace('fa-pause', 'fa-play')
        document.querySelector('.music img').style.animationPlayState = 'paused' //暂停旋转
        audio.pause()
      }
      //上一首下一首
      if ($(this)[0].classList[1] == 'fa-backward') {
        if (musicIndex == 0) { //第一首不能上一首
          return
        } else {
          loadMusic(musicList[--musicIndex].url)
          loadControl(musicList[musicIndex])
          console.log('当前', musicIndex);
          document.querySelector('.music img').style.animationPlayState = 'running' //开始旋转
          $('.fa-play')[0].classList.replace('fa-play', 'fa-pause') //转换播放按钮

        }
      }
      if ($(this)[0].classList[1] == 'fa-forward') {

        getMusic(++musicIndex)
        console.log('当前', musicIndex);
        document.querySelector('.music img').style.animationPlayState = 'running' //开始旋转
        $('.fa-play')[0].classList.replace('fa-play', 'fa-pause') //转换播放按钮
      }
      // 颜色
      $(this).css({
        'color': '#DBDBDB'
      })
    }).on('mouseup', function (e) {
      //颜色
      $(this).css({
        'color': '#fff'
      })
    })
    //请求音乐数据
    function getMusic(index) {
      $.ajax({
        url: 'https://api.uomg.com/api/rand.music?sort=热歌榜&format=json',
        type: 'get',
        success: function (res) {
          musicList.push(res.data)
          loadControl(musicList[index])
          loadMusic(musicList[index].url)
        },
        fail: function (err) {
          console.log(err);
        }
      })
    }
    getMusic(musicIndex)

    //渲染控件文字图片
    function loadControl(musicObj) {
      // console.log('musicObj', musicObj);
      $('.banner span').html(musicObj.name + ' - ' + musicObj.artistsname)
      $('.music img').attr('src', musicObj.picurl)
    }

    //渲染音频
    function loadMusic(url) {
      audio.pause()
      audio.setAttribute('src', url)
      audio.play()
    }
  </script>
</body>

</html>